package com.kum.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kum.domain.constant.ChatMsg;
import com.kum.domain.constant.MsgActionEnum;
import com.kum.domain.entity.SysChatMsg;
import com.kum.mapper.SysChatMsgMapper;
import com.kum.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @Package com.kum.service
 * @auhter 枯木Kum
 * @date 2021/5/8-9:36 AM
 * <p>...</p>
 */

@Service
public class SysChatMsgService {

    @Autowired
    private SysChatMsgMapper chatMsgMapper;

    public String save(SysChatMsg chatMsg) {
        return chatMsgMapper.save(chatMsg).getId();
    }

    public void delete(String id) {
        chatMsgMapper.deleteById(id);
    }

    /**
     * 获取我和我的朋友的聊天记录
     *
     * @param friendUserId 朋友的UserId
     * @param number       条数
     * @return
     */
    public Page findMyChatMsgOfFriend(String myUserId,String friendUserId, Integer number) {
        Specification<SysChatMsg> specification = (Specification<SysChatMsg>) (root, query, criteriaBuilder) -> {
            Predicate friendIsSendUserIdPredicate = criteriaBuilder
                    .equal(root.get("sendUserId").as(String.class), friendUserId);
            Predicate IAmSendUserIdPredicate = criteriaBuilder
                    .equal(root.get("sendUserId").as(String.class), myUserId);
            Predicate friendIsAcceptUserIdPredicate = criteriaBuilder
                    .equal(root.get("acceptUserId").as(String.class), friendUserId);
            Predicate IAmAcceptUserIdPredicate = criteriaBuilder
                    .equal(root.get("acceptUserId").as(String.class), myUserId);
            // A: 朋友是发送消息方，我是接收方
            // B: 我是发送消息方，朋友是接收方
            Predicate a = criteriaBuilder.and(friendIsSendUserIdPredicate, IAmAcceptUserIdPredicate);
            Predicate b = criteriaBuilder.and(IAmSendUserIdPredicate, friendIsAcceptUserIdPredicate);
            query.where(criteriaBuilder.or(a, b));
            query.orderBy(criteriaBuilder.asc(root.get("createTime").as(Date.class)));
            return query.getRestriction();
        };


        PageRequest pageRequest = PageRequest.of(0, number);
        Page result = chatMsgMapper.findAll(specification, pageRequest);
        return result;
    }


    /**
     * 获取我的未读消息列表
     *
     * @param myUserId
     * @return {
     * key: 好友ID,
     * value: {
     * 'unReadNum': 1,    // 未读消息数量
     * 'msgs': []         // 未读消息列表
     * }
     * }
     */
    public Map<String, JSONObject> findMyChatMsgOfUnReadData(String myUserId) {
        List<SysChatMsg> myChatsDataList = chatMsgMapper.findByAcceptUserIdAndUnRead(myUserId);
        Map<String, JSONObject> result = new HashMap<>();

        myChatsDataList.forEach(item -> {
            String sendUserId = item.getSendUserId();
            JSONObject object = new JSONObject();
            if (!result.containsKey(sendUserId)) {
                object.put("userId", sendUserId);
                object.put("unReadNum", 1);
                JSONArray array = new JSONArray();
                array.add(item);
                object.put("msgs", array);
            } else {
                object = result.get(sendUserId);
                object.put("unReadNum", object.getInteger("unReadNum") + 1);
                JSONArray msgs = object.getJSONArray("msgs");
                msgs.add(item);
            }
            System.out.println("sendUserId：" + sendUserId);
            result.put(sendUserId, object);
        });

        return result;


    }

    /**
     * 将某位好友的信息全部设置为已读
     * @param acceptUserId
     * @param friendUserId
     */
    public void signedMsgByFriendId(String acceptUserId, String friendUserId) {
        List<SysChatMsg> msgList = chatMsgMapper.findByAcceptUserIdAndSendUserIdAndUnRead(acceptUserId, friendUserId);
        msgList.forEach(msg -> {
            msg.setStatus(ChatMsg.READ);
            chatMsgMapper.save(msg);
        });

    }


}
